package org.wxl.service.impl;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.wxl.comment.BussinessTypeConstant;
import org.wxl.domain.fileInfoEntity;
import org.wxl.mapper.FileInfoMapper;
import org.wxl.service.FileUploadService;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.UUID;
/**
 * @author 王学良
 */
@Service
@AllArgsConstructor
public class FileUploadServiceImpl  implements FileUploadService {
    private static final String UPLOAD_DIR = "uploads";
    private static final String FLAG = ".";

    /**
     * 文件扩展名与存储目录的映射
     */
    private static final String[] IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif"};
    private static final String[] VIDEO_EXTENSIONS = {".mp4", ".avi", ".flv", ".webm"};
    private static final String[] AUDIO_EXTENSIONS = {".mp3", ".wav", ".ogg"};
    private static final String[] DOCUMENT_EXTENSIONS = {".pdf", ".doc", ".docx", ".xls", ".xlsx"};
    private final FileInfoMapper fileInfoMapper;

    /**
     * 通用文件上传方法
     * @param file 上传的文件对象
     * @param uploaderUuid 上传者的 UUID
     * @param businessType 业务类型
     * @return FileInfo 对象，包含文件信息
     * @throws IllegalArgumentException 文件类型不合法
     */
    public fileInfoEntity uploadFile(MultipartFile file, String uploaderUuid, String businessType) throws IllegalArgumentException, IOException {
        // 校验文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 获取原始文件名并处理扩展名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.contains(FLAG)) {
            throw new IllegalArgumentException("文件名格式不正确");
        }
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(FLAG)).toLowerCase();


        /*
          根据文件扩展名确定存储目录
         */
        String baseDir = getString(fileExtension);

        // 生成新的文件名
        String fileUuid = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = fileUuid + fileExtension;

        // 构建存储路径
        String uploadRoot = System.getProperty("user.dir") + File.separator + UPLOAD_DIR;
        Path uploadPath = Paths.get(uploadRoot, baseDir);

        // 创建目录（如果不存在）
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 保存文件
        Path targetPath = uploadPath.resolve(newFileName);
        file.transferTo(targetPath.toFile());

        // 创建 FileInfo 对象并保存到数据库
        fileInfoEntity fileInfoEntity = new fileInfoEntity();
        fileInfoEntity.setUuid(fileUuid);
        fileInfoEntity.setOriginalFilename(originalFilename);
        fileInfoEntity.setFileType(file.getContentType());
        fileInfoEntity.setStoragePath(targetPath.toString());
        fileInfoEntity.setUploaderUuid(uploaderUuid);
        fileInfoEntity.setFileSize(file.getSize());
        fileInfoEntity.setUploadTime(LocalDateTime.now());
        fileInfoEntity.setBusinessType(businessType);
        // 默认状态为审核中
        fileInfoEntity.setStatus("0");
        // 默认访问权限为个人可见
        fileInfoEntity.setAccessPermission("0");

        fileInfoMapper.insert(fileInfoEntity);
        // 改为返回相对路径
        return fileInfoEntity;

    }

    @Override
    public String updateFileInfo(fileInfoEntity fileInfoEntity) {
        //这里主要是更新视频的主题，简介，关键词
        try{
            fileInfoEntity fileInfoEntity1 = fileInfoMapper.selectById(fileInfoEntity.getUuid());
            fileInfoEntity1.setTheme(fileInfoEntity.getTheme());
            fileInfoEntity1.setRemark(fileInfoEntity.getRemark());
            fileInfoEntity1.setKeywords(fileInfoEntity.getKeywords());
            fileInfoMapper.updateById(fileInfoEntity1);
            return "更新成功";
        }catch (Exception e)
        {
            return "更新失败";
        }
    }

    private static String getString(String fileExtension) {
        String baseDir;
        if (Arrays.asList(IMAGE_EXTENSIONS).contains(fileExtension)) {
            baseDir = "images";
        } else if (Arrays.asList(VIDEO_EXTENSIONS).contains(fileExtension)) {
            baseDir = "videos";
        } else if (Arrays.asList(AUDIO_EXTENSIONS).contains(fileExtension)) {
            baseDir = "audio";
        } else if (Arrays.asList(DOCUMENT_EXTENSIONS).contains(fileExtension)) {
            baseDir = "documents";
        } else {
            throw new IllegalArgumentException("不支持的文件类型: " + fileExtension);
        }
        return baseDir;
    }
    @Override
    public String uploadVideoThumbnail(MultipartFile file, String uploaderUuid , String videoUuid) throws IOException {
        try {
            fileInfoEntity fileInfoEntity = uploadFile(file, uploaderUuid, BussinessTypeConstant.USER_VIDEO_THUMBNAIL);
            fileInfoEntity fileInfoEntity1 = fileInfoMapper.selectById(videoUuid);
            fileInfoEntity1.setThumbnailPath(fileInfoEntity.getStoragePath());
            return videoUuid;
        }catch (Exception e)
        {
            return "上传缩略图失败";
        }
    }

}
